package com.msb.bf;

import com.google.common.collect.Lists;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author: zhaoyi
 * @create: 2020-05-08 13:54
 * @description: ThreadLocal的中弱引用，防止了内存泄漏
 *               ThreadLocal是一个用于为每个线程提供独立变量副本的工具类
 **/

public class ThreadLocalWeakReference {

    public static void main(String[] args) throws InterruptedException {

        //线程本地变量，自己线程独有的 跟其他线程无关
        ThreadLocal<List<Integer>> localList = new ThreadLocal<>();
        //如果在这里set是给main线程本地变量赋值

        new Thread(() -> {
            //set 调用为本线程的线程本地变量赋值
            System.out.println(localList);
            localList.set(Lists.newArrayList());
            List<Integer> integers = localList.get();
            for (int i = 0; i < 1000; i++) {
                integers.add(i);
            }
            System.out.println(Thread.currentThread().getName() + integers.size());

            //使用完需要 remove 避免内存泄漏
            localList.remove();

        },"Thread-A").start();

        TimeUnit.SECONDS.sleep(10);


        new Thread(() -> {
            System.out.println(localList);
            List<Integer> integers = localList.get();
            if (localList.get() != null){
                System.out.println(Thread.currentThread().getName() + integers.size());
            }else {
                //自己没有赋值所以是null
                System.out.println(Thread.currentThread().getName() + integers);
            }

        },"Thread-B").start();


    }


}
